﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections;

using FL.DBModule;
using FL.DBModule.Sys;
using FL.SysEntity;
using FL.Common;

namespace FL.Bussiness.Sys
{
    public partial class BUser : BaseBussnies
    {

        /// <summary>
        /// 构造函数
        /// </summary>
        public BUser()
        {
            this.entity = new SysUser();
        }


        /// <summary>
        /// 判断用户密码的有效性
        /// </summary>
        /// <param name="user_id"></param>
        /// <returns></returns>
        public int GetUserPasswordLimitDay(Guid? user_id)
        {
            try
            {
                IList<t_sys_user_password_history> list = this.GetEntitys<t_sys_user_password_history>("user_id='" + user_id.ToString() + "'");

                System.DateTime? lastChangDate = list.Select(p => p.chang_date).Max();
                if (lastChangDate.HasValue)
                {
                    return (lastChangDate.Value.AddDays(90) - DateTime.Today).Days;
                }
            }
            catch (Exception e)
            { }
            return -1;

        }

        /// <summary>
        /// 数据验证
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns>返回字符串</returns>
        public override string CheckData(BaseEntity entity)
        {
            SysUser user = entity as SysUser;
            if (string.IsNullOrEmpty(user.username))
            {
                return "用户名不能为空!";
            }
            else if (string.IsNullOrEmpty(user.password))
            {
                return "密码不能为空!";
            }
            return base.CheckData(user);
        }
        /// <summary>
        /// 判断用户名是否已存在
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns>true:已存在 false:不存在</returns>
        public bool IsExist(SysUser entity)
        {
            return GetEntityByCondition("username='" + entity.username + "'") != null;
        }
        /// <summary>
        /// 判断用户名是否已存在
        /// </summary>
        /// <param name="LoginName">用户名</param>
        /// <returns>true:已存在 false:不存在</returns>
        public bool IsExist(string LoginName)
        {
            return GetEntityByCondition("username='" + LoginName + "'") != null;
        }
        /// <summary>
        /// 修改用户时判断用户名登录名是否已存在
        /// </summary>
        /// <param name="LoginName">用户名</param>
        /// <returns>true:已存在 false:不存在</returns>
        public bool IsExist(string LoginName, Guid userId)
        {
            return GetEntityByCondition("username='" + LoginName + "' and id!='" + userId + "'") != null;
        }
        /// <summary>
        /// 用户登录时判断是否过期
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public bool IsExpire(SysUser user)
        {
            return GetEntityByCondition("username='" + user.username + "' and password='" + user.password + "' and is_expire=1") != null;
        }
        /// <summary>
        /// 判断用户名和密码是否正确
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns>true:成功 false:失败</returns>
        public SysUser GetDatUserByLoginNameAndPwd(SysUser entity)
        {
            return GetEntityByCondition("username ='" + entity.username + "' and Password='" + entity.password + "'") as SysUser;
        }
        /// <summary>
        /// 切换用户
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns>true:成功 false:失败</returns>
        public SysUser GetDatUserByLoginName(SysUser entity)
        {
            return GetEntityByCondition("id ='" + entity.id + "'") as SysUser;
        }


        /// <summary>
        /// 根据名称判断用户是否存在
        /// </summary>
        /// <param name="uName"></param>
        /// <returns></returns>
        public SysUser GetDatUserByUName(string username)
        {
            return GetEntityByCondition("username='" + username + "'") as SysUser;
        }
        /// <summary>
        /// 判断用户名和密码是否正确
        /// </summary>
        /// <param name="Name">登录名</param>
        /// <param name="Password">密码</param>
        /// <returns></returns>
        public SysUser GetDatUserByLoginNameAndPwd(string Name, string Password)
        {
            SysUser user = null;
            if (!string.IsNullOrEmpty(Name) && string.IsNullOrEmpty(Password))
            {
                user = new SysUser();
                user.username = Name;
                user.password = ExtendMethods.GetMd5Hash(Password);
                user = GetDatUserByLoginNameAndPwd(user);

            }
            return user;
        }


        /// <summary>
        /// 密码修改
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        public void ChangePassword(string username, string password)
        {
            if (!string.IsNullOrEmpty(username) && string.IsNullOrEmpty(password))
            {
                SysUser user = GetDatUserByName(username);
                user.password = ExtendMethods.GetMd5Hash(password);
                this.entity = user;
                this.Update();
            }
        }

        /// <summary>
        /// 根据用户ID获取系统功能权限集合
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>返回系统功能权限集合</returns>
        public IList<t_sys_function> GetFunctionByUserId(Guid userId)
        {
            return this.GetEntitysBySqlComm<t_sys_function>("Select * from v_sys_function where  user_id='" + userId + "' and (is_menu<>'N' or is_menu is Null) order by sort");
            //return GetEntitysByCondition("UserID='" + userId + "'") as IList<VSysfunction>;
        }

        /// <summary>
        /// 根据用户ID获取系统功能权限集合
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>返回系统功能权限集合</returns>
        public bool ExistFunction(Guid userId, Guid functionId)
        {
            var list = this.GetEntitysBySqlComm<t_sys_function>("Select * from V_SysFunction where  UserID='" + userId + "' and functionId='" + functionId + "'");
            if (list == null)
            { return false; }
            if (list.Count == 0)
            { return false; }
            return true;
            //return GetEntitysByCondition("UserID='" + userId + "'") as IList<VSysfunction>;
        }


        /// <summary>
        /// 获取用户的功能权限信息
        /// </summary>
        /// <param name="userID">用户</param>
        /// <param name="functionID">功能</param>
        /// <returns></returns>
        public IList<v_sys_user_function_dataright> GetUserFunction(Guid? userID, Guid? functionID)
        {
            return this.GetEntitys<v_sys_user_function_dataright>(string.Format("user_id='{0}' and function_id='{1}'", userID, functionID));
        }


        #region 数据权限条件生成
        /// <summary>
        /// 获取部门数据的条件
        /// </summary>
        /// <param name="UserID">用户ID</param>
        /// <param name="EntityName">实体</param>
        /// <param name="functionID">功能ID</param>
        /// <returns></returns>
        public virtual string GetUserFunctionDataDeptInfo(Guid? UserID, Guid? functionID,string paraConditon="")
        {
            //t_set_entity _entity = this.GetEntityByCondition<t_set_entity>("name='" + EntityName + "'");
            //IList<TableInfoStruc> _list = this.GetEntitys<TableInfoStruc>("TableName='" + EntityName + "'");
            IList<v_sys_user_function_dataright> Rights = GetUserFunction(UserID, functionID);
            string condition = "is_stop<>0 and (path is null or path<>'')";
            if (Rights != null)
            {
                System.Text.StringBuilder strCondition = new System.Text.StringBuilder("");
                foreach (var entity in Rights)
                {
                    if (strCondition.ToString() != "")
                    {
                        strCondition.Append(" OR ");
                    }

                    switch (entity.operate_range_type)
                    {
                        //全部
                        case "0":
                            strCondition.Append(" 1=1 ");
                            break;
                        //本部门
                        case "2":
                            strCondition.Append(string.Format("id in (select id from dbo.[ufn_get_cureent_user_depts]('{0}'))", UserID));
                            break;
                        //本公司
                        case "3":
                            break;
                        //本大区/事业部
                        case "4":
                            break;
                        //自定义部门
                        case "5":
                            strCondition.Append(string.Format("cast(id as varchar(50)) in (select value from dbo.[[ufn_split_string]]('{0}'))", entity.dept_range));
                            break;
                        default:
                            strCondition.Append(" 1=1 ");
                            break;

                    }
                }
                condition = strCondition.ToString();
                
                
            }
            else
            {
                condition =  "";
            }

            System.Data.DataTable dt = null;
            if(paraConditon!="")
                dt = this.GetDataBySqlComm(string.Format("select *,SUBSTRING([path],1,len([path])-4) as parent_path from t_base_department {0}", string.IsNullOrEmpty(condition) ? "where ( " + paraConditon + " ) Order by sort" : " where (" + condition + ") and ( " + paraConditon + " ) Order by sort desc"));
            else
                dt = this.GetDataBySqlComm(string.Format("select *,SUBSTRING([path],1,len([path])-4) as parent_path from t_base_department {0}", string.IsNullOrEmpty(condition) ? "" : " where " + condition));
            if (dt!=null&&dt.Rows.Count>0)
            {
                return FL.Common.Globals.Dtb2Json(dt);
            }
            return "{}";
        }


        /// <summary>
        /// 获取数据过滤条件
        /// </summary>
        /// <param name="UserID">用户ID</param>
        /// <param name="EntityName">实体</param>
        /// <param name="functionID">功能ID</param>
        /// <returns></returns>
        public virtual string GetUserFunctionDataRightCondition(Guid? UserID, Guid? functionID, string EntityName)
        {
            t_set_entity _entity = this.GetEntityByCondition<t_set_entity>("name='" + EntityName + "'");
            IList<TableInfoStruc> _list = this.GetEntitys<TableInfoStruc>("TableName='" + EntityName + "'");
            IList<v_sys_user_function_dataright> Rights = GetUserFunction(UserID, functionID);
            if (Rights != null)
            {
                System.Text.StringBuilder strCondition = new System.Text.StringBuilder("");
                foreach (var entity in Rights)
                {
                    //如果没有实体配置对应的部门字段和操作者ID，则直接自定义条件
                    
                    if ((entity.operate_range_type!="7")&&(_entity == null || (string.IsNullOrEmpty(_entity.dept_field) && string.IsNullOrEmpty(_entity.user_field))))
                    {
                        _entity = new t_set_entity();
                        _entity.name = EntityName;
                        
                        if( _list.Where(p=>p.ColName.ToLower()=="dept_id").Count()>0)
                        {
                            _entity.dept_field = "dept_id";
                        }
                        if (_list.Where(p => p.ColName.ToLower() == "add_user").Count() > 0)
                        {
                            _entity.user_field = "add_user";
                        }
                        //strCondition.Append(string.IsNullOrEmpty(entity.define_condition) ? "" : entity.define_condition);
                        //continue;
                        if ((string.IsNullOrEmpty(_entity.dept_field) && string.IsNullOrEmpty(_entity.user_field)))
                        {
                            if (strCondition.ToString() != "")
                            {
                                strCondition.Append(" or ");
                            }
                            strCondition.Append(string.IsNullOrEmpty(entity.define_condition) ? "1=1" : entity.define_condition);
                            continue;
                        }
                    }
                    if (strCondition.ToString() != "")
                    {
                        strCondition.Append(" or ");
                    }

                    switch (entity.operate_range_type)
                    {
                        //全部
                        case "0":
                            strCondition.Append(" 1=1 ");
                            break;
                        //本人
                        case "1":
                            if (!string.IsNullOrEmpty(_entity.user_field))
                            {
                                strCondition.Append(string.Format("{1}='{0}'", UserID, _entity.user_field));
                            }
                            else
                            {
                                if (_list.Where(p => p.ColName.ToLower() == "add_user").Count() == 1)
                                {
                                    strCondition.Append(string.Format("add_user='{0}'", UserID));
                                }
                                else
                                {
                                    strCondition.Append(" 1=1 ");//如果不存在人员字段，则不限制
                                }
                            }
                            //
                            break;
                        //本部门(含本子部门下的)
                        case "2":
                            if (!string.IsNullOrEmpty(_entity.dept_field))
                            {
                                strCondition.Append(string.Format("{1} in (select id from dbo.[ufn_get_cureent_user_depts]('{0}'))", UserID, _entity.dept_field));
                            }
                            else
                            {
                                if (_list.Where(p => p.ColName.ToLower() == "dept_id").Count()==1)
                                {
                                    strCondition.Append(string.Format("{1} in (select id from dbo.[ufn_get_cureent_user_depts]('{0}'))",UserID, "dept_id"));
                                }
                                if (_list.Where(p => p.ColName.ToLower() == "department_id").Count() == 1)
                                {
                                    strCondition.Append(string.Format("{1} in (select id from dbo.[ufn_get_cureent_user_depts]('{0}'))",UserID, "department_id"));
                                }
                                else
                                {
                                    strCondition.Append(" 1=1 ");//如果不存在部门字段，则不限制
                                }
                            }
                            break;
                        //本公司
                        case "3":

                            if (!string.IsNullOrEmpty(_entity.dept_field))
                            {
                                strCondition.Append(string.Format("{1} in (select id from dbo.[ufn_get_cureent_user_depts]('{0}'))", UserID, _entity.dept_field));
                            }
                            else
                            {
                                if (_list.Where(p => p.ColName.ToLower() == "dept_id").Count() == 1)
                                {
                                    strCondition.Append(string.Format("{1} in (select id from dbo.[ufn_get_cureent_user_depts]('{0}'))", UserID, "dept_id"));
                                }
                                if (_list.Where(p => p.ColName.ToLower() == "department_id").Count() == 1)
                                {
                                    strCondition.Append(string.Format("{1} in (select id from dbo.[ufn_get_cureent_user_depts]('{0}'))", UserID, "department_id"));
                                }
                                else
                                {
                                    strCondition.Append(" 1=1 ");//如果不存在部门字段，则不限制
                                }
                            }
                            //strCondition.Append(" 1=1 ");
                            break;
                        //本大区/事业部
                        case "4":

                            strCondition.Append(" 1=1 ");
                            break;
                        //自定义部门
                        case "5":
                            if (!string.IsNullOrEmpty(_entity.dept_field))
                            {
                                strCondition.Append(string.Format("cast({1} as varchar(50)) in (select value from dbo.[ufn_split_string]('{0}','@'))", entity.dept_range, _entity.dept_field));
                            }
                            else
                            {
                                if (_list.Where(p => p.ColName.ToLower() == "dept_id").Count() == 1)
                                {
                                    strCondition.Append(string.Format("cast({1} as varchar(50)) in (select value from dbo.[ufn_split_string]('{0}','@'))", entity.dept_range, "dept_id"));
                                }
                                if (_list.Where(p => p.ColName.ToLower() == "department_id").Count() == 1)
                                {
                                    strCondition.Append(string.Format("cast({1} as varchar(50)) in (select value from dbo.[ufn_split_string]('{0}','@'))", entity.dept_range, "department_id"));
                                }
                                else
                                {
                                    strCondition.Append(" 1=1 ");//如果不存在部门字段，则不限制
                                }
                            }
                            break;
                        //自定义条件
                        case "6":
                            if (string.IsNullOrEmpty(entity.define_condition))
                            {
                                strCondition.Append("("+entity.define_condition.Replace("@UserID",UserID==null?Guid.Empty.ToString():UserID.ToString())+")");
                            }
                            else
                            {
                                strCondition.Append(" 1=1 ");
                            }
                            break;
                        //外部客户
                        case "7":
                            SysUser user = (new BUser()).GetDatUserByUserId((Guid)UserID);
                            string cusotmerNo = user.customer_no;
                            strCondition.Append(string.Format(" customer_no='{0}' ", cusotmerNo));
                            break;
                        default:
                            strCondition.Append(" 1=1 ");
                            break;

                    }
                }
                return strCondition.ToString();
            }
            else
            {
                return "";
            }
            //return "";
        }
        #endregion

        /// <summary>
        /// 根据用户ID获取用户角色集合
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>返回用户角色集合</returns>
        public IList<SysRole> GetUserRoleByUserId(Guid userId)
        {
            return GetEntitysBySqlComm<SysRole>("Select * from v_sys_user_role where user_id='" + userId + "'");
        }
        /// <summary>
        /// 根据用户ID获取用户信息
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>返回用户实体对象</returns>
        public SysUser GetDatUserByUserId(Guid userId)
        {
            return GetEntityByCondition<SysUser>("id='" + userId + "'") as SysUser;
        }
        /// <summary>
        /// 根据用户名获取用户实体对象
        /// </summary>
        /// <param name="name">用户名</param>
        /// <returns>用户实体对象</returns>
        public SysUser GetDatUserByName(string username)
        {
            return GetEntityByCondition<SysUser>("username='" + username + "'") as SysUser;
        }


        /// <summary>
        /// 根据邮箱获取用户实体对象
        /// </summary>
        /// <param name="email">邮箱</param>
        /// <returns>用户实体对象</returns>
        public SysUser GetDatUserByEmail(string email)
        {
            return GetEntityByCondition<SysUser>("email='" + email + "'") as SysUser;
        }


        /// <summary>
        /// 检测token的合法性
        /// </summary>
        /// <param name="token">口令</param>
        /// <returns></returns>
        public string CheckToken(string token,string ip_address, out SysUser user)
        {
            user = new SysUser();
            if (string.IsNullOrEmpty(token))
            {
                return string.Format(messageTemplate,"-1:口令不能为空".Split(':'));
            }
            //t_sys_token token_entity = this.GetEntityByCondition<t_sys_token>("ip_address='" + ip_address + "' and token='" + token.Replace("\"", "") + "' and isnull(is_expire,'NZ')<>'Y'");
            t_sys_token token_entity = this.GetEntityByCondition<t_sys_token>("ip_address='" + ip_address + "' and token='" + token.Replace("\"", "") + "'");
            if (token_entity == null)
            {
                return string.Format(messageTemplate,"-2:口令失效".Split(':'));
            }
            if(System.DateTime.Now>token_entity.last_action_time.AddDays(1))
            {
                return string.Format(messageTemplate,"-2:口令失效".Split(':'));
            }
            this.RunSqlCommand("update t_sys_token set last_action_time='" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' where token='" + token + "' ");
            user = this.GetEntityByCondition<SysUser>("username='" + token_entity.user_name + "'");
            return "";
        }


        private string messageTemplate = "{{retCode:{0},retMsg:'{1}'}}";
        /// <summary>
        /// 获取当前操作者的令牌
        /// </summary>
        /// <param name="loginUser"></param>
        /// <returns></returns>
        public string PostToken(SysUser loginUser,string ip_address="")
        {
            return GenerateToken(loginUser);
            //try
            //{
            //    string user_name = loginUser.username;
            //    string user_password = loginUser.password;
            //    Guid token_id = Guid.NewGuid();
            //    if (loginUser != null)
            //    {
            //        t_sys_token token = new t_sys_token();
            //        //BaseBussnies bll = new BaseBussnies();
            //        this.RunSqlCommand("update t_sys_token set is_expire='Y'  where user_name='" + user_name + "' and  isnull(is_expire,'NZ')<>'Y'");
            //        token.id = Guid.NewGuid();
            //        token.user_name = user_name;
            //        token.login_time = System.DateTime.Now;
            //        token.last_action_time = System.DateTime.Now;
            //        token.ip_address = ip_address;
            //        token.token = token_id.ToString();
            //        this.Insert(token);
            //        return "{retCode:1,retMsg:'" + token_id.ToString() + "'}";
            //    }
            //    else
            //    {
            //        return "{retCode:0,retMsg:'提交失败'}";
            //    }
            //}
            //catch (Exception e)
            //{
            //    return "{retCode:-4,retMsg:'" + e.Message + "'}";
            //}
        }
        /// <summary>
        /// 获取当前操作者的令牌
        /// </summary>
        /// <param name="loginUser"></param>
        /// <returns></returns>
        public string PostToken(string username,string password, string ip_address = "")
        {
            SysUser user = new SysUser { username=username,password=password};
            return GenerateToken(user);
            //try
            //{
            //    string user_name = username;
            //    string user_password = password;
            //    Guid token_id = Guid.NewGuid();
            //    if (user_name != null)
            //    {
            //        t_sys_token token = new t_sys_token();
            //        //BaseBussnies bll = new BaseBussnies();
            //        this.RunSqlCommand("update t_sys_token set is_expire='Y'  where user_name='" + user_name + "' and  isnull(is_expire,'NZ')<>'Y'");
            //        token.id = Guid.NewGuid();
            //        token.user_name = user_name;
            //        token.login_time = System.DateTime.Now;
            //        token.last_action_time = System.DateTime.Now;
            //        token.ip_address = ip_address;
            //        token.token = token_id.ToString();
            //        this.Insert(token);
            //        return "{retCode:1,retMsg:'" + token_id.ToString() + "'}";
            //    }
            //    else
            //    {
            //        return "{retCode:0,retMsg:'提交失败'}";
            //    }
            //}
            //catch (Exception e)
            //{
            //    return "{retCode:-4,retMsg:'" + e.Message + "'}";
            //}
        }

        /// <summary>
        /// 生成用户令牌
        /// </summary>
        /// <param name="loginUser">用户对象</param>
        /// <returns>令牌字串</returns>
        public string GenerateToken(SysUser loginUser)
        {
            try
            {
                if (loginUser == null)
                {
                    FL.Log.XTrace.WriteLine("---------------用户LOGIN--------------------");
                    FL.Log.XTrace.WriteLine("---------------提交失败------------------");
                    FL.Log.XTrace.WriteLine("---------------" + System.DateTime.Now + "--------------------");
                    FL.Log.XTrace.WriteLine("---------------end--------------------");
                    return string.Format(messageTemplate,"0:提交失败!".Split(':'));
                }

                string user_name = loginUser.username;
                string user_password = loginUser.password;

                FL.Log.XTrace.WriteLine("---------------用户LOGIN--------------------");
                FL.Log.XTrace.WriteLine("---------------" + user_name + "--------------------");
                FL.Log.XTrace.WriteLine("---------------" + System.DateTime.Now + "--------------------");
                FL.Log.XTrace.WriteLine("---------------end--------------------");

               
                SysUser user = this.GetDatUserByName(user_name);
                if (user == null)
                {
                    return string.Format(messageTemplate,"-1:用户不存在!".Split(':'));
                }
                if (user.expire_date != null && user.expire_date < System.DateTime.Now && user.expire_date != DateTime.Parse("1900-01-01"))
                {
                    return string.Format(messageTemplate,"-2:该用户己经失效!".Split(':'));
                }
                if (!user_password.VerifyMd5Hash(user.password))
                {
                    return string.Format(messageTemplate,("-3:用户密码错误，请重新输入!").Split(':'));
                }

                Guid token_id = Guid.NewGuid();


                if (loginUser != null)
                {
                    t_sys_token token = new t_sys_token();
                    //BaseBussnies bll = new BaseBussnies();
                    this.RunSqlCommand("update t_sys_token set is_expire='Y',last_action_time='" + System.DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "' where user_name='" + user_name + "' ");
                    token.id = Guid.NewGuid();
                    token.user_name = user_name;
                    token.login_time = System.DateTime.Now;
                    token.last_action_time = System.DateTime.Now;
                    token.token = token_id.ToString();
                    this.Insert(token);
                    //token = 
                    return string.Format(messageTemplate, ("1:" + token_id.ToString()+"").Split(':'));
                }
                else
                {
                    return string.Format(messageTemplate,"0:提交失败".Split(':'));
                }
            }
            catch (Exception e)
            {
                return string.Format(messageTemplate,("-4:" + e.Message).Split(':'));
            }
        }

    }
}
